﻿using System;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Security.Permissions;
using System.IO;
using System.Diagnostics;


/*
 * 
 * Thema:
 * Serialisierung - finden für dataSet
 * 
 * */

namespace MagicCardManager
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class MCMView : Form
    {
        private MCMController m_controller = null;
        NameValueCollection m_nameValueConnection = null;
        //////////////////////////////////////////////////////////////////////////////////
        // Forms
        private Form_AddSet FormAddSet = new Form_AddSet();
        private Form_AddEdition FormAddEdition = new Form_AddEdition();
        private AddCard FormAddCard = new AddCard();
        #region PROPERTIES
        public NameValueCollection Config
        {
            get
            {
                return (m_nameValueConnection);
            }
        }

        public dsDb SDDB
        {
            get
            {
                return (dsDb);
            }
            set
            {
                dsDb = value;
            }
        }
        #endregion PROPERTIES

        public string test = null;

        public MCMView()
        {
            m_nameValueConnection = ConfigurationManager.AppSettings;
            SqLiteHandle sqlite = new SqLiteHandle(m_nameValueConnection.Get("database"));


            InitializeComponent();
            initialize();
        }

        private void initialize()
        {
            InitializeWebbrowser_Main();
            InitializeBackgoundWorker_DataCardGrid();
            InitializebackgroundWorker_Search_CardGrid();
            InitializebackgroundWorker_Update_CardGrid();
        }

        private void InitializeWebbrowser_Main()
        {
            webBrowser_Main.AllowWebBrowserDrop = false;
            webBrowser_Main.IsWebBrowserContextMenuEnabled = true;
            webBrowser_Main.WebBrowserShortcutsEnabled = false;
            webBrowser_Main.ObjectForScripting = this;
#if DEBUG
            webBrowser_Main.ScriptErrorsSuppressed = false;
#else 
            webBrowser_Main.ScriptErrorsSuppressed = true;
#endif
        }

        private void InitializeBackgoundWorker_DataCardGrid()
        {
            backgroundWorker_DataCardGrid = new BackgroundWorker();
            backgroundWorker_DataCardGrid.DoWork += new DoWorkEventHandler(backgroundWorker_DataCardGrid_DoWork);
            backgroundWorker_DataCardGrid.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_DataCardGrid_RunWorkerCompleted);
        }

        private void backgroundWorker_DataCardGrid_DoWork(object sender, DoWorkEventArgs e)
        {
            dsDb = m_controller.FillCardGrid();
        }
        private void backgroundWorker_DataCardGrid_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string result;
            using (StringWriter sw = new StringWriter())
            {
                dsDb.Tables["cardGrid"].WriteXml(sw);
                result = sw.ToString();
            }
            webBrowser_Main.Document.InvokeScript("parseXml", new String[] { result });
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        private void InitializebackgroundWorker_Search_CardGrid()
        {
            backgroundWorker_Search_CardGrid = new BackgroundWorker();
            backgroundWorker_Search_CardGrid.DoWork += new DoWorkEventHandler(backgroundWorker_Search_CardGrid_DoWork);
            backgroundWorker_Search_CardGrid.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_Search_CardGrid_RunWorkerCompleted);
        }
        private void backgroundWorker_Search_CardGrid_DoWork(object sender, DoWorkEventArgs e)
        {
            object[] args = (object[])e.Argument;
            dsDb = m_controller.Search_tbl_CardGrid(args[0].ToString(), args[1].ToString());
            int test = 0;
        }
        private void backgroundWorker_Search_CardGrid_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string result;
            using (StringWriter sw = new StringWriter())
            {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
                if (this.dsDb.Tables["cardGrid"].Rows.Count != 0 && null != this.dsDb.Tables["cardGrid"].Rows.Count)
                {
                    this.dsDb.Tables["cardGrid"].WriteXml(sw);
                    result += sw.ToString();
                }
            }
            webBrowser_Main.Document.InvokeScript("CLAPP_parseXml", new String[] { result });
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        private void InitializebackgroundWorker_Update_CardGrid()
        {
            backgroundWorker_Update_CardGrid = new BackgroundWorker();
            backgroundWorker_Update_CardGrid.DoWork += new DoWorkEventHandler(backgroundWorker_Update_CardGrid_DoWork);
            backgroundWorker_Update_CardGrid.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_Update_CardGrid_RunWorkerCompleted);
        }
        private void backgroundWorker_Update_CardGrid_DoWork(object sender, DoWorkEventArgs e)
        {
            dsDb = m_controller.UpdateCardGrid((DataRow)e.Argument);
        }
        private void backgroundWorker_Update_CardGrid_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            int test = 0;
        }



        //////////////////////////////////////////////////////////////////////////////////////
        // Events
        private void Form1_Load(object sender, EventArgs e)
        {
            m_controller = new MCMController(this);
            m_controller.UpdateMainData += new MCMController.UpdateMainDataGrideventhandler(OnMainDataChange);

            Uri nav = new Uri(Application.StartupPath);
            webBrowser_Main.Navigate(Application.StartupPath + "\\dat\\index.html");

            this.backgroundWorker_DataCardGrid.RunWorkerAsync();
        }


        private void OnMainDataChange(object sender, MainDataGridEventArgs e)
        {
            this.dsDb = (dsDb)e.DBDataSet;
        }


        //////////////////////////////////////////////////////////////////////////////////////
        // Menu Events
        private void addSetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAddSet.ShowDialog();
        }

        private void addEditionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAddEdition.ShowDialog();

        }

        private void addCardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAddCard.ShowDialog();

        }




        /////////////////////////////////////////////////////////////////////////////////////
        // Browser Handling
        /// <summary>
        /// Event für das Generieren und Laden der Html Seiten.
        /// </summary>
        /// <param name="cls">class Name für ein Tag.</param>
        /// <param name="page">Seite, die geladen werden soll.</param>
        public void WB_LoadPage(string cls, string page)
        {
            webBrowser_Main.Document.InvokeScript("loadContent", new String[] { cls, page });
        }
        /// <summary>
        /// Event für das Generieren und Laden der Editionsliste
        /// </summary>
        public void WB_LoadEditionList()
        {
            webBrowser_Main.Document.InvokeScript("loadContent", new String[] { ".item", "_content/_site/edition_list.html" });
        }

        /// <summary>
        /// Event für das Generieren und Laden der Jahresliste
        /// </summary>
        public void WB_LoadYearList()
        {
            webBrowser_Main.Document.InvokeScript("loadContent", new String[] { ".item", "_content/_site/year_list.html" });
        }

        /// <summary>
        /// Event für das Generieren und Laden der Cardliste
        /// </summary>
        public void WB_LoadCardList()
        {
            webBrowser_Main.Document.InvokeScript("loadContent", new String[] { ".item", "_content/_site/card_list.html" });
        }

        public void WB_LoadCard()
        {
            webBrowser_Main.Document.InvokeScript("loadContent", new String[] { ".item", "_content/_site/card.html" });
        }

        /// <summary>
        /// Ändert Werte einer Karte oder fügt eine neue Karte hinzu (wenn keine card_id mitgegeben wird)
        /// </summary>
        /// <param name="xml"></param>
        public void WB_ChangeCardValue(string xml)
        {
            DataSet ds = new DataSet();
            StringReader stream = new StringReader(xml);
            ds.ReadXml(stream);

            int h = 2;
            //webBrowser_Main.Document.InvokeScript("loadContent", new String[] { ".item", "_content/_site/card.html" });
        }

        public void WB_Card_ListLiveSearch(string col, string val)
        {
            if (val == null || col == "") return;
            object[] args = {col, val};

            this.backgroundWorker_Search_CardGrid.Dispose();
            this.backgroundWorker_Search_CardGrid = null;
            InitializebackgroundWorker_Search_CardGrid();
            this.backgroundWorker_Search_CardGrid.RunWorkerAsync(args);

            Console.WriteLine("##########################################");
        }


        /// <summary>
        /// Senden vom Client an Browser
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser_Main.Document.InvokeScript("CL_test", new String[] { "called from client code" });
        }
    }


    //#region EVENTARGS
    //public class MainDataGridSearchDoWorkEventArgs : DoWorkEventArgs
    //{
    //    public string k;
    //    public string v;

    //    public MainDataGridEventArgs(object j)
    //    {
            
    //    }

    //}
    //#endregion EVENTARGS

    public class MainDataGridSearchEventArgs// : EventArgs
    {
        public string k;
        public string v;

    }
}
